package hb.watcher.monitor;


import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import com.mysql.jdbc.Statement;


import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.TabActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.MediaStore.Audio;

import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import android.widget.ImageButton;
import android.widget.TabHost;

import android.widget.Toast;

@SuppressWarnings("deprecation")
public class WatchMyToonActivity extends TabActivity {
	
	// all the public stuff here
	public TabHost tabhost;
	public List<CharTabs> CharTabsList = new ArrayList<CharTabs>();
	public DBConnection dbconn = null;
	public Config conf = new Config();
	
	private boolean debug = false;
	
	public String Url;
	public String DBName;
	public String UserName;
	public String Password;
	
	public DBConnection GetConn()
	{
		return dbconn;
	}

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        if(debug)
        {
	        Url = "mysql.lima-city.de";
	        DBName = "db_261638_1";
	        UserName = "USER261638";
	        Password = "hpwupKvM";
        }
        
     
        ImageButton Imgb = (ImageButton) findViewById(R.id.ImageButton1);
        Imgb.setClickable(false);
        
        if(CheckConfig())
        {
        	dbconn = new DBConnection(Url,DBName, UserName, Password, this);
        	dbconn.Connect();
        	dbconn.StartUpdater();
        	Imgb.setClickable(true);
  
        }else
        {
        	ShowDialog();
        }
        
        Imgb.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	if(CheckConfig())
                {
	            	CharLoader load = new CharLoader();
	            	load.execute();
                }else
                {
                	ShowDialog();
                }
            }
        });
    }
    
    @Override
    public void onBackPressed()  {
        
    	AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    	alertDialog.setTitle("Close WatchMyToon");
    	alertDialog.setMessage("Do you really want to exit?");
    	alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {  
    	    @Override  
    	    public void onClick(DialogInterface dialog, int which) { 
    	    	dialog.dismiss();  
    	        finish();
    	    }  
    	});
    	alertDialog.setButton2("No", new DialogInterface.OnClickListener() {  
    	    @Override  
    	    public void onClick(DialogInterface dialog, int which) {  
    	    	dialog.dismiss();  
    	    }  
    	});
    	alertDialog.show();
        
    }

    /**
     * Checks if the application is being sent in the background (i.e behind
     * another application's Activity).
     * 
     * @param context the context
     * @return <code>true</code> if another application will be above this one.
     */
    public static boolean isApplicationSentToBackground(final Context context) {
      
      ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
      List<RunningTaskInfo> tasks = am.getRunningTasks(1);
      if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
          return true;
        }
      }

      return false;
    }

    int HELLO_ID = 1;
    public void sendnotify(ChatActivity what, String itickerText, String titel, String text)
    {
    	try
    	{
    	Context context = getApplicationContext();
    	PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);

    		
    	if(isApplicationSentToBackground(getApplicationContext()) || !pm.isScreenOn())
    	{
	    	String ns = Context.NOTIFICATION_SERVICE;
	    	NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
	    	
	    	int icon = R.drawable.notification;        // icon from resources
	    	CharSequence tickerText = itickerText;              // ticker-text
	    	long when = System.currentTimeMillis();         // notification time
	    	
	    	
	    	Notification notification = new Notification(icon, tickerText, when);
	    	
	    	
	    	
	    	      // application Context
	    	CharSequence contentTitle = titel;  // message title
	    	CharSequence contentText = text;      // message text
	    	
	    	
	    	Intent notificationIntent = new Intent(this,WatchMyToonActivity.class );
	    	//Intent notificationIntent = new Intent(what,ChatActivity.class );
	    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

	    	
	 
	    	notification.defaults |= Notification.DEFAULT_SOUND;
	    	notification.defaults |= Notification.DEFAULT_VIBRATE;
	    	notification.flags |= Notification.FLAG_AUTO_CANCEL;

	    	
	    	notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
	    	   
	
	    	mNotificationManager.notify(HELLO_ID, notification);
	    	
	    	
	    	try
	    	{
	    		
		         if(!pm.isScreenOn())
		         {
			
				        WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE,"MyLock");
			
				                            wl.acquire(10000);
				        WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MyCpuLock");
			
				                 wl_cpu.acquire(10000);
		         }
	    	}catch(Exception ex)
	    	{
	    		
	    	}

	         HELLO_ID = HELLO_ID+1;

    	}
    	}catch(Exception ex)
    	{
    		
    	}
    	
    	
    	/*Intent notificationIntent = new Intent(this, WatchMyToonActivity.class);
    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    	notification.defaults |= Notification.DEFAULT_SOUND;
    	notification.defaults |= Notification.DEFAULT_VIBRATE;
    	notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
    	notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
    	//long[] vibrate = {0,100,200,300};
    	//notification.vibrate = vibrate;
    	notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);*/
    }
    private void ShowDialog()
    {
    	AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    	alertDialog.setTitle("Setup missing");
    	alertDialog.setMessage("Please add databaseinformation first");
    	alertDialog.setButton("OK", new DialogInterface.OnClickListener() {  
    	    @Override  
    	    public void onClick(DialogInterface dialog, int which) {  
    	        dialog.dismiss();  
    	        Intent myIntent = new Intent(getBaseContext(), SetupActivity.class);
                startActivityForResult(myIntent, 0);
    	       
    	    }  
    	});
    	
    	alertDialog.show();
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.setup:    
            	Intent SetupIntent = new Intent(getBaseContext(), SetupActivity.class);
                startActivityForResult(SetupIntent, 0);
                                break;
            case R.id.Add:     Toast.makeText(this, "Not implemented yet", Toast.LENGTH_SHORT).show();
                                break;
            case R.id.Del: 
            	
            	Toast.makeText(this, "Not implemented yet", Toast.LENGTH_SHORT).show();
                                break;
            case R.id.chardetail: 
            	
            	Toast.makeText(this, "Not implemented yet", Toast.LENGTH_SHORT).show();
                                break;
            case R.id.notimanager: 
            	
            	Intent NotiIntent = new Intent(getBaseContext(), NotificationMan.class);
                startActivityForResult(NotiIntent, 0);
      
                                break;
        }
        return true;
    }
    
    public static boolean notEmpty(String s) {
    	 return (s != null && s.length() > 0);
    	}
    
    private boolean CheckConfig()
    {

    	if(!notEmpty(Url) && !notEmpty(DBName) && !notEmpty(UserName) && !notEmpty(Password))
        {
	    	conf.load();
	        Url = conf.get("url");
	        DBName = conf.get("DBName");
	        UserName = conf.get("UserName");
	        Password = conf.get("Password");
        }
        
        if(notEmpty(Url) && notEmpty(DBName) && notEmpty(UserName) && notEmpty(Password))
        {
        	return true;
        }else
        {
        	return false;
        }
    }
    
    
    
    private class CharLoader extends AsyncTask<Void, Void, Void> {
    	
    	CharSequence  text = null;
    	int duration = Toast.LENGTH_SHORT;
    	
    	
		private ProgressDialog dialog;
		
    	@Override
    	protected void onPreExecute()
    	{
    		
    		
    		dialog = ProgressDialog.show(WatchMyToonActivity.this, "", 
                    "Loading Online Chars ...", true);
	
    	}
    	
    	private void getChars()
    	{
    		try {
        		
    			String statement = "SELECT * FROM `TABToons` WHERE `dtLastUpdate` >= date_sub( CURRENT_TIMESTAMP , INTERVAL 45 SECOND )";
        		ResultSet rs = dbconn.DBSyn(true,statement);
		        
		    		while (rs.next()) {
		    			
		    			boolean bfound = false;
						
		    			int nCharID = rs.getInt("nToonId");
		    			String charName = rs.getString("szName");
		    			
		    				for (CharTabs _CharTabs: CharTabsList) {
		    					
		    					if(_CharTabs.getToonId() == nCharID)
		    						bfound = true;
		    					
		    					if(bfound)
		    						break;
		    				}
		    			
		    			if(!bfound)
		    			{
		    				
		    				CharTabs chars = new CharTabs(nCharID,charName);
		    				CharTabsList.add(chars);
		    			}
						
						
		    		}
		    	
		    		rs.close();
        
        		
        		
        	}catch(Exception ex)
    		{
        		
    		}
    	}
    	
		@Override
		protected Void doInBackground(Void... params) {
			
			try {
				if(dbconn.IsConnected())
				{
					 getChars();
						 
				}else
				{
					if(dbconn.Connect())
					{
						 getChars();
						 
					}else
					{
						text = dbconn.getLastError();
					}
				}
				
			}catch(Exception e) {
				
				text = e.getLocalizedMessage();
				
			}
			
			
			return null;
		}
		
		private boolean CreateTabs(String TabName, int toonId)
		{
			
			try
			{
			TabHost tabhost = getTabHost();
			Resources res = getResources();
			Intent intent;
			tabhost.setup();

			Bundle params = new Bundle();
			params.putInt("toonId", toonId);
			params.putString("Url", Url);
			params.putString("toonname", TabName);
			params.putString("DBName", DBName);
			params.putString("UserName", UserName);
			params.putString("Password", Password);
			params.putSerializable("dbConn", dbconn);

			
			
			intent = new Intent().setClass(getBaseContext(), CharsActivity.class);
		    intent.putExtras(params);

		    
		    TabHost.TabSpec spec = tabhost.newTabSpec(TabName).setIndicator(TabName)
              .setContent(intent);
		        
		        
		    tabhost.addTab(spec);
		    
		    for(int i = 0; i < getTabWidget().getTabCount(); i++)
		    {
		    	
		    }
		      	
			return true;
			
			}catch(Exception ex)
			{
				return false;
			}
		}
		
		@Override
		protected void onPostExecute(Void result) {
		
			dialog.dismiss();
			if(text != null)
			{
				Toast toast = Toast.makeText(getApplicationContext(), text, duration);
				toast.show();
			}else
			{
				for (CharTabs _CharTabs: CharTabsList) {
					
					if(!_CharTabs.TabCreated())
					{
						if(CreateTabs(_CharTabs.getToonName(), _CharTabs.getToonId()));
							_CharTabs.TabCreated(true);
					}
				}
			}
			
			
		}
    
    }
    

    
}